<template>
  <mt-button @click="pay" :size="size"  :money="money" :type="type" :disabled="disabled"><slot></slot></mt-button>
</template>
<script>
  import {getPaymentParams} from '../../api/api'
  import {Toast} from 'mint-ui'
  export default {
    name:'pay-button',
    props:{

      size:{
        type:String,
        default:'small'
      },
      type:{
        type:String,
        default:'primary'
      },
      disabled:{
        type:Boolean,
        default:false
      },
      money:{
        type:Number,
        default:0
      },
      systemId:{
        type:String,
        default:'wx-plan1'
      },
      orderId:{
        type:String,
        default:''
      }
    },
    data(){
      return {

      }
    },

    methods:{
      pay(){
        let vm=this;
        new Promise((resovle, reject) => {
          let params = {
            amount: vm.money*100,
            body: '信息数据',
            systemId: vm.systemId,
            openId: sessionStorage.getItem('openid'),
            orderId:vm.orderId
          };
          getPaymentParams(params).then((res) => {

            if (res.data.result) {
              resovle(res.data.data);
            } else {
              reject(res.data.msg);
            }
          });
        }).then((data) => {
          let order=data.order;

          delete data.order;
          if (typeof WeixinJSBridge == 'undefined') {

            if (document.addEventListener) {

              document.addEventListener('WeixinJSBridgeReady', this.onBridgeReady, false);

            } else if (document.attachEvent) {

              document.attachEvent('WeixinJSBridgeReady', this.onBridgeReady);

              document.attachEvent('onWeixinJSBridgeReady', this.onBridgeReady);

            }
          } else {

            this.onBridgeReady(data, () => {
              console.log('支付成功');

              vm.$emit('pay-ok',order.id);

            });
          }
        })
      },
      onBridgeReady(params, onPayOk) {
        let vm=this;
        WeixinJSBridge.invoke(
          'getBrandWCPayRequest', params, function (rs) {


            if (rs.err_msg == 'get_brand_wcpay_request:ok') {
                if(onPayOk!=null&&(typeof onPayOk=='function'))
                    onPayOk()

            } else {
              vm.$emit('pay-failed',params);
              Toast({
                position: 'bottom',
                message: '取消支付'
              });
              console.log('取消支付');

            }
          })
      },
    }
  }
</script>
